/**
 * 优化版地区API服务
 * 解决大数据量传输问题，支持分层按需加载
 */

import request from '@/utils/request'
import type { OptimizedRegion, OptimizedRegionSearchResult } from '@/types/regionOptimized'

/**
 * 地区数据接口响应格式
 */
export interface RegionResponse<T = any> {
  code: number
  msg: string
  data: T
  timestamp?: number
}

/**
 * 省份信息（精简版）
 */
export interface Province {
  id: number
  name: string
  initial: string
  pinyin: string
}

/**
 * 城市信息
 */
export interface City {
  id: number
  name: string
  parent_id: number
  initial: string
  pinyin: string
  has_children: boolean
}

/**
 * 区县信息
 */
export interface District {
  id: number
  name: string
  parent_id: number
  initial: string
  pinyin: string
}

/**
 * 地址路径节点
 */
export interface AddressPathNode {
  id: number
  name: string
  level: number
}

/**
 * 完整地址路径
 */
export interface FullAddressPath {
  target: {
    id: number
    name: string
    level: number
  }
  path: AddressPathNode[]
}

/**
 * 地区API服务类
 */
class RegionOptimizedService {
  /**
   * 获取省份列表（精简版）
   */
  async getProvinces(): Promise<Province[]> {
    try {
      const response = await request.get<RegionResponse<Province[]>>(
        '/api/system/region-optimized/provinces'
      )

      // 确保响应数据结构正确
      if (response && response.data) {
        if (response.data.code === 0 && Array.isArray(response.data.data)) {
          return response.data.data
        } else if (Array.isArray(response.data)) {
          // 兼容直接返回数组的情况
          return response.data
        }
      }

      // 处理204状态码（无内容）的情况
      if (response?.status === 204) {
        return []
      }

      throw new Error(response?.data?.msg || '获取省份列表失败')
    } catch (error) {
      // 处理网络错误或API错误
      if (
        error instanceof Error &&
        (error.message.includes('404') || error.message.includes('204'))
      ) {
        return []
      }
      throw error
    }
  }

  /**
   * 获取城市列表（按省份）
   */
  async getCities(provinceId: number): Promise<City[]> {
    try {
      const response = await request.get<RegionResponse<City[]>>(
        `/api/system/region-optimized/cities/${provinceId}`
      )

      // 检查响应结构
      if (response && response.data) {
        if (response.data.code === 0 && Array.isArray(response.data.data)) {
          return response.data.data
        } else if (Array.isArray(response.data)) {
          // 兼容直接返回数组的情况
          return response.data
        }
      }

      // 处理204状态码（无内容）的情况
      if (response?.status === 204) {
        return []
      }

      throw new Error(response?.data?.msg || '获取城市列表失败')
    } catch (error) {
      // 处理网络错误或API错误
      if (
        error instanceof Error &&
        (error.message.includes('404') || error.message.includes('204'))
      ) {
        return []
      }
      throw error
    }
  }

  /**
   * 获取区县列表（按城市）
   */
  async getDistricts(cityId: number): Promise<District[]> {
    try {
      const response = await request.get<RegionResponse<District[]>>(
        `/api/system/region-optimized/districts/${cityId}`
      )

      // 检查响应结构
      if (response && response.data) {
        if (response.data.code === 0 && Array.isArray(response.data.data)) {
          return response.data.data
        } else if (Array.isArray(response.data)) {
          // 兼容直接返回数组的情况
          return response.data
        }
      }

      // 处理204状态码（无内容）的情况
      if (response?.status === 204) {
        return []
      }

      throw new Error(response?.data?.msg || '获取区县列表失败')
    } catch (error) {
      // 如果是204状态码或者空数据，返回空数组而不是抛出错误
      if (error && typeof error === 'object' && 'response' in error) {
        const errorWithResponse = error as { response: { status: number } }
        if (errorWithResponse.response && errorWithResponse.response.status === 204) {
          return []
        }
      }

      // 处理网络错误或API错误
      if (error instanceof Error && error.message.includes('404')) {
        return []
      }

      // 其他错误才抛出
      throw error
    }
  }

  /**
   * 搜索地区（支持模糊搜索）
   */
  async searchRegions(
    keyword: string,
    level?: number,
    limit?: number
  ): Promise<OptimizedRegionSearchResult[]> {
    try {
      const params = new URLSearchParams()
      params.append('keyword', keyword)
      if (level) params.append('level', level.toString())
      if (limit) params.append('limit', limit.toString())

      const response = await request.get<RegionResponse<OptimizedRegionSearchResult[]>>(
        `/api/system/region-optimized/search?${params}`
      )
      if (response.data.code === 0) {
        return response.data.data
      }
      throw new Error(response.data.msg || '搜索地区失败')
    } catch (error) {
      throw error
    }
  }

  /**
   * 获取完整地址路径
   */
  async getFullPath(regionId: number): Promise<FullAddressPath> {
    try {
      const response = await request.get<RegionResponse<FullAddressPath>>(
        `/api/system/region-optimized/full-path/${regionId}`
      )
      if (response.data.code === 0) {
        return response.data.data
      }
      throw new Error(response.data.msg || '获取地址路径失败')
    } catch (error) {
      throw error
    }
  }

  /**
   * 批量获取地区信息
   */
  async batchGetRegions(ids: number[]): Promise<OptimizedRegion[]> {
    try {
      const response = await request.post<RegionResponse<OptimizedRegion[]>>(
        '/api/system/region-optimized/batch',
        {
          ids: ids.join(','),
        }
      )
      if (response.data.code === 0) {
        return response.data.data
      }
      throw new Error(response.data.msg || '批量获取地区信息失败')
    } catch (error) {
      throw error
    }
  }

  /**
   * 清除地区缓存
   */
  async clearCache(): Promise<void> {
    try {
      const response = await request.delete('/api/system/region-optimized/cache')
      if (response.data.code !== 0) {
        throw new Error(response.data.msg || '清除缓存失败')
      }
    } catch (error) {
      throw error
    }
  }
}

// 创建单例实例
export const regionOptimizedApi = new RegionOptimizedService()

// 默认导出
export default regionOptimizedApi
